<template class="subject">
  <div id="unit" v-loading="loading">
    <template>
      <div>
        <el-row :gutter="20" type="flex">
          <el-col :span="12">
            <el-button
              type="custom"
              @click="showEditDialog('add')"
              v-if="$store.getters.userType == 1"
              >新增组织架构</el-button
            >
          </el-col>
          <!-- <el-col :span="10" :offset="4">
            <ImportButtons type="unit" />
          </el-col> -->
        </el-row>
      </div>
      <el-container>
        <el-aside width="400px" style="padding-top: 10px">
          <div class="custom-tree-container">
            <div class="hedtitle">
              <!-- <span
                class="hedname"
                @click="
                  userListQuery.deptId = ''
                  getUserList()
                "
                >组织架构</span
              > -->
              <!-- <p class="show-son">
                显示子部门：
                <el-switch
                  v-model="userListQuery.isChildUser"
                  active-color="var(--colorA1)"
                  active-value="1"
                  inactive-value="2"
                ></el-switch>
              </p> -->
              <span class="edit">操作</span>
            </div>
            <el-tree
              :data="companyTableData"
              ref="vueTree"
              :checkedKeys="defaultCheckedKeys"
              :props="defaultProps"
              node-key="id"
              accordion
              :expand-on-click-node="false"
              :default-expanded-keys="expandedArr"
              @node-expand="nodeExpand"
              @node-collapse="nodeCollapse"
            >
              <span
                class="custom-tree-node"
                slot-scope="{ node, data }"
                @click="lineClick(node)"
              >
                <span class="node-names" :title="node.data.name">{{
                  node.data.name
                }}</span>
                <span width="200" class="edit">
                  <el-button
                    v-if="setDisabled(data) && $button('108')"
                    type="text"
                    title="新增"
                    style="color: var(--colorA2)"
                    class="el-icon-plus"
                    @click.stop="() => showEditDialog('add', data)"
                  ></el-button>
                  <el-button
                    type="text"
                    class="el-icon-minus"
                    title="删除"
                    style="color: var(--colorA2)"
                    v-if="$button('112')"
                    @click.stop="() => showDeleDialog(node, data)"
                  ></el-button>
                  <el-button
                    type="text"
                    style="color: var(--colorA2)"
                    title="编辑"
                    class="el-icon-edit"
                    v-if="$button('111')"
                    @click.stop="() => showEditDialog('', data)"
                  ></el-button>
                </span>
              </span>
            </el-tree>
          </div>
        </el-aside>
        <el-main style="padding: 0 0 20px 20px">
          <el-table
            :data="userTableData"
            style="width: 100%"
            max-height="600"
            stripe
          >
            <el-table-column
              fixed
              prop="userName"
              label="用户"
              show-overflow-tooltip
            >
              <template slot-scope="scope">{{
                scope.row | showUserInfo
              }}</template>
            </el-table-column>
            <!-- <el-table-column fixed prop="account" label="登录名">
                        </el-table-column>-->
            <el-table-column
              fixed
              prop="menuRoleList"
              label="角色"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <p>
                  <el-tag
                    size="small"
                    type="danger"
                    disable-transitions
                    v-for="(item, index) in scope.row.menuRoleList"
                    :key="index"
                    >{{ item.name }}</el-tag
                  >
                </p>
              </template>
            </el-table-column>
            <el-table-column
              prop="createName"
              label="部门"
              show-overflow-tooltip
            >
              <template slot-scope="scope">{{
                scope.row.deptFullName | deptFormat
              }}</template>
            </el-table-column>
            <el-table-column
              prop="createTime"
              label="创建时间"
              width="180"
            ></el-table-column>
          </el-table>
          <Pagination
            style="margin-top: 20px"
            v-show="parseInt(userPageObj.count) > 0"
            :total="parseInt(userPageObj.count)"
            @change="getList"
            :page.sync="userListQuery.page"
            :limit.sync="userListQuery.limit"
          />
        </el-main>
      </el-container>
    </template>

    <el-dialog
      :title="addOrEdit ? '部门管理-新增' : '部门管理-编辑'"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      width="700px"
      @close="$reset('temp')"
    >
      <el-form ref="temp" :model="temp" :rules="rules" label-width="110px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="temp.name" placeholder="请输入部门名称"></el-input>
        </el-form-item>
        <el-form-item label="上一级部门" class="top_unit">
          <el-popover
            placement="bottom-start"
            v-model="treeFlag"
            class="orgTree"
            trigger="click"
          >
            <el-tree
              :data="companyTableData"
              :props="defaultProps"
              :expand-on-click-node="false"
              accordion
              node-key="id"
              style="width: 300px"
              @node-click="handleNodeClickDep"
            ></el-tree>
            <el-input
              slot="reference"
              ref="input"
              v-model="treeName"
              clearable
              :readonly="true"
              style="width: 100%"
              placeholder="请选择上一级部门"
            ></el-input>
          </el-popover>

          <i
            @click.stop="closeName"
            class="el-icon-circle-close"
            v-if="treeName"
          ></i>
          <i class="el-icon-arrow-down" v-else></i>
        </el-form-item>
        <el-form-item label="部门类型">
          <el-radio-group v-model="temp.type">
            <el-radio label="1">学院（校区）</el-radio>
            <el-radio label="2">系（部）</el-radio>
            <el-radio label="3">教研室</el-radio>
            <el-radio label="4">其他</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="本级部门编码" prop="code">
          <el-input v-model="temp.code"></el-input>
        </el-form-item>
        <el-form-item label="负责人" prop="manager">
          <div class="user-wrap">
            <p v-show="initialValue.userId.length == 0">请选择人员</p>
            <el-tag
              v-for="tag in initialValue.userId"
              :key="tag.manager || tag.userId"
              closable
              type="danger"
              disable-transitions
              @close="handleClose(tag)"
              >{{ tag.managerName || tag.userName }}</el-tag
            >
          </div>
          <el-button
            class="user-select-button"
            type="custom"
            plain
            @click="handleSelect()"
            >选择人员</el-button
          >
          <!-- <el-input
            v-model="temp.manager"
                    ></el-input>-->
          <!-- <div class="manager-box" @click="handleSelect">
              <el-tag type="danger" v-show="managerName" closable  @close="handleClose(tag)">{{managerName}}</el-tag>
                    </div>-->
        </el-form-item>
        <el-form-item label="排序">
          <el-input
            type="number"
            v-model="temp.sort"
            placeholder="请输入排序"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          v-show="!addOrEdit"
          type="custom"
          v-preventReClick
          @click="handleUpdate('temp')"
          >提 交</el-button
        >
        <el-button
          v-show="addOrEdit"
          type="custom"
          v-preventReClick
          @click="handleAdd('temp')"
          >新 增</el-button
        >
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <UserSelect
      ref="userSelect"
      radioType
      :initialValue="initialValue"
      @e-userData="setUserId"
    />
  </div>
</template>

<script>
import {
  tbDeptQuery,
  tbDeptAdd,
  tbDeptUpdate,
  tbDeptDelete,
  tbDeptQueryById,
} from '@/api/admin/system/unitManage.js'
import { tbSysUserQuery } from '@/api/admin/user/user-manage.js'
import Bus from '@/utils/bus.js'

export default {
  created() {
    this.getList()
    // this.getUserList();
  },
  mounted() {
    this.$bus.$on('refreshUnitList', () => {
      this.getList()
    })
  },
  beforeDestroy() {
    this.$bus.$off('refreshUnitList')
  },
  components: {
    UserSelect: () => import('@/components/userSelect'),
    ImportButtons: () => import('@/components/importButtons'),
  },
  data() {
    return {
      initialValue: {
        userId: [],
      },
      temp: {
        type: '1',
      },
      listQuery: {
        pId: '0',
      },
      userListQuery: {
        page: 1,
        limit: 10,
        isChildUser: '1',
        deptId: '',
      },
      userPageObj: {},
      companyTableData: [],
      userTableData: [],
      tableData2: [],
      defaultProps: {
        children: 'childList',
        label: 'name',
      },
      dialogVisible: false,
      dialogFormVisible: false,
      pageObj: {},
      addOrEdit: true,
      rules: {
        name: [
          {
            required: true,
            message: '请输入部门名称',
            trigger: 'blur',
          },
          {
            min: 1,
            max: 15,
            message: '长度在 1 到 15 个字符',
            trigger: 'blur',
          },
        ],
        code: [
          {
            required: true,
            message: '请输入本级部门编码',
            trigger: 'blur',
          },
          {
            min: 1,
            max: 15,
            message: '长度在 1 到 15 个字符',
            trigger: 'blur',
          },
        ],
        genre: [
          {
            required: true,
            message: '请选择部门属性',
            trigger: 'change',
          },
        ],
      },
      treeFlag: false,
      treeName: '',
      seldisabled: false,
      defaultCheckedKeys: [],
      loading: false,
      superiorCode: '0',
      managerName: '',
      initialValue: {
        userId: [],
      },
      expandedArr: [],
    }
  },
  methods: {
    // 调用选人
    handleSelect() {
      Bus.$emit('userSelect')
    },
    // 获取返回数据回显
    setUserId(v) {
      this.initialValue.userId = []
      if (v.hasOwnProperty('userId')) {
        this.initialValue.userId = v.id
      } else {
        this.initialValue.userId.push(v)
      }
      this.temp.manager = v.id
    },
    //    setUserId(v){
    //     if(v){
    //         this.temp.manager = v.id;
    //         this.managerName = v.userName;
    //         this.initialValue={
    //             userId:v
    //         }
    //     }
    // },
    // 清除负责人
    // handleClose(){
    //     this.temp.manager = "";
    //      this.managerName ="";
    // },
    handleClose(row) {
      this.initialValue.userId = this.initialValue.userId.filter(
        (v) => v.id != row.id,
      )
      this.temp.manager = ''
      this.managerName = ''
    },
    //获取列表
    getList() {
      // return
      tbDeptQuery(this.listQuery).then((res) => {
        // let { data } = res.data
        // let { deptFullData, userType } = this.$store.getters
        // if (userType == 1) {
        //   //超管
        //   this.companyTableData = data
        //   this.getUserList()
        // } else {
        //   //普通管理员
        //   if (!data.length || data.hasOwnProperty('childList')) return
        //   let fullDept = data[0].childList
        //   if (
        //     deptFullData.hasOwnProperty('childList') &&
        //     deptFullData.childList.length
        //   ) {
        //     let schoolDept = deptFullData.childList[0].id
        //     this.companyTableData = fullDept.filter((v) => v.id == schoolDept)
        //     this.getUserList(schoolDept)
        //   }
        // }
        this.companyTableData = res.data.data;
        if (this.companyTableData.length) {
          this.expandedArr.push(this.companyTableData[0].id)
        }
        this.getUserList()
      })
    },
    getUserList(deptId) {
      this.userListQuery.deptId = deptId || ''
      tbSysUserQuery(this.userListQuery).then((res) => {
        this.userTableData = res.data.data
        this.userPageObj = res.data
      })
    },
    getTreeId(data) {
      this.listQuery.deptId = data.id
      this.getList()
    },
    //行点击
    lineClick(data) {
      this.$bus.$emit('sendDeptId', data.key)
      this.getUserList(data.key)
    },
    //更新数据默认展开节点
    nodeExpand(v) {
      this.expandedArr.push(v.id)
    },
    //更新数据默认收起节点
    nodeCollapse(v) {
      let idx = this.expandedArr.indexOf(v.id)
      if (idx == -1) return
      this.expandedArr.splice(idx, 1)
    },
    //新增/编辑弹框
    showEditDialog(type, row) {
      var data = {}
      if (type == 'add') {
        this.initialValue.userId = []
        this.temp.manager = ''
        if (row) {
          this.queryNameById(row.id)
          data.pid = row.id
          data.code = ''
        } else {
          this.temp.code = ''
          this.temp.pid = ''
          this.treeName = ''
        }
        this.addOrEdit = true

        this.seldisabled = false
      } else {
        if (row.manager) {
          var rowdata = JSON.parse(JSON.stringify(row))
          rowdata.id = rowdata.manager
          this.initialValue.userId = [rowdata]
          this.temp.manager = row.manager
        } else {
          this.initialValue.userId = []
          this.temp.manager = ''
        }

        data = row
        data.code = row.code
        this.addOrEdit = false
        // this.treeName=row.pname;
        this.queryNameById(row.pid)
        this.temp.pid = row.pid
        if (row.pid == 0) {
          this.seldisabled = false
        } else {
          this.seldisabled = true
        }
      }

      this.superiorCode = data.pid ? data.pid : 0
      this.temp = { ...data }

      this.dialogFormVisible = true
    },
    //查询上一级
    queryNameById(id) {
      tbDeptQueryById(id).then((res) => {
        if (res.data.data[0] == null) {
          this.treeName = ''
        } else {
          this.treeName = res.data.data[0].name
        }
      })
    },
    //新增
    handleAdd(temp) {
      this.$refs[temp].validate((valid) => {
        if (valid) {
          if (this.treeName == '') {
            this.temp.pid = 0
          }

          tbDeptAdd(this.temp).then((res) => {
            if (res.data.code == 0) {
              this.$message.success(res.data.msg)
            } else {
              this.$message.error(res.data.msg)
            }
            this.dialogFormVisible = false
            this.getList()
          })
          // companyTableData.push({
          //     name:this.temp.name,
          //     pid:this.temp.pid,
          //     content:this.temp.content
          // })
          // this.dialogFormVisible = false;
        }
      })
    },
    //编辑
    handleUpdate(temp) {
      this.$refs[temp].validate((valid) => {
        if (valid) {
          var data = {
            id: this.temp.id,
            name: this.temp.name,
            code: this.temp.code,
            pid: this.temp.pid,
            genre: this.temp.genre,
            sort: this.temp.sort,
            manager: this.temp.manager,
            type: this.temp.type,
          }
          tbDeptUpdate(data).then((res) => {
            if (res.data.msg == '0') {
              this.$message.success('删除成功！')
            } else if (res.data.msg == '1') {
              this.$message.error('当前部门下有子部门，无法删除！')
            } else if (res.data.msg == '2') {
              this.$message.error('当前部门下有用户，无法删除！')
            } else {
              this.$message.success('操作成功！')
            }
            this.dialogFormVisible = false
            this.getList()
          })
        }
      })
    },

    // 选中上一级部门
    handleNodeClickDep(val) {
      var path = val.deptFullnamepath.split('/')
      var arr = []
      path.forEach((e) => {
        if (e) {
          arr.push(e)
        }
      })

      if (arr.length >= 4) {
        this.$message({
          message: '组织架构最多四层级别，请重新选择！',
          type: 'warning',
        })
        return false
      }
      this.treeName = val.name
      this.temp.genre = val.genre
      this.seldisabled = true
      this.treeFlag = false
      this.temp.pid = val.id
    },
    // 清空上一级部门
    closeName() {
      this.treeName = ''
      this.temp.pid = ''
      this.temp.genre = ''
      this.seldisabled = false
    },
    //删除
    showDeleDialog(node, row) {
      var text = '删除部门将影响平台功能，请慎重操作，是否删除?'
      // 删除有子节点的  父节点
      if (node.data.pid != 0) {
        text = '删除部门将影响平台功能，请慎重操作，是否删除?'
      }
      this.temp = { ...row }
      this.$confirm(text, '提示', {
        type: 'warning',
      })
        .then((_) => {
          tbDeptDelete(this.temp.id).then((res) => {
            // if (res.data.code == 0) {
            //   this.$message.success(res.data.msg);
            // } else {
            //   this.$message.error(res.data.msg);
            // }
            if (res.data.msg == '0') {
              this.$message.success('删除成功！')
            } else if (res.data.msg == '1') {
              this.$message.error('当前部门下有子部门，无法删除！')
            } else if (res.data.msg == '2') {
              this.$message.error('当前部门下有用户，无法删除！')
            }
            this.getList()
          })
        })
        .catch((_) => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    //  限制长度
    setDisabled(data) {
      var showType = true
      var live = data.deptFullpath.split('/')
      if (live.length <= 5) {
        showType = true
      } else {
        showType = false
      }
      return showType
    },
  },
}
</script>
<style scoped>
.user-wrap {
  display: inline-block;
  width: 420px;
  border: 1px solid #dcdfe6;
  border-radius: 5px;
  overflow: hidden;
  min-height: 40px;
  cursor: not-allowed;
}
.user-wrap p {
  line-height: 40px;
  color: #bbb;
  text-indent: 10px;
}
.user-wrap span {
  margin: 0 5px;
}
.user-select-button {
  float: right;
}
span.custom-tree-node {
  width: 100%;
}
span.edit {
  float: right;
  padding-right: 5%;
  position: absolute;
  right: 0;
}
.custom-tree-container {
  padding: 0px 10px 10px 10px;
  background: #f5f7fa;
}

span.edit .el-button--text {
  padding: 0;
}
.hedtitle {
  border-bottom: 1px solid #ebeef5;
  color: #585858;
  font-weight: 800;
  font-size: 14px;
  position: relative;
  /* padding-bottom: 7px; */
  padding: 5px 0;
}
.hedname {
  padding-left: 20px;
}
.show-son {
  /* float: left; */
  display: inline-block;
}
</style>
<style >
#unit .el-tree-node__content {
  padding: 5px 0;
}
#unit .el-form-item.top_unit i.el-icon-circle-close,
.el-form-item.top_unit i.el-icon-arrow-down {
  position: absolute;
  right: 10px;
  top: 13px;
  cursor: pointer;
}
#unit .el-col.el-col-6 {
  border-right: 1px solid #ebeef5;
  overflow: auto;
  height: 700px;
}
#unit .el-col.el-col-18 {
  padding-left: 15px;
}
#unit .node-names {
  float: left;
  max-width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-block;
}
#unit .manager-box {
  border: 1px solid #dcdfe6;
  border-radius: 5px;
  padding-left: 20px;
  height: 45px;
  cursor: pointer;
}
#unit .el-tree {
  height: 600px;
  overflow-y: auto;
}
</style>

<style>
.left-menu {
  display: block;
}
</style>